package com.wsjj.yjh;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

//      使用reduce实现max和maxBy的功能。
//需要在linux中打开端口  命令为：  nc -lk 7777
public class TransReduce {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        SingleOutputStreamOperator<WaterSensor> map = env.socketTextStream("hadoop102", 7777)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
                    }
                });
        KeyedStream<WaterSensor, String> keyedStream = map.keyBy(value -> value.id);
//max
//        keyedStream.reduce(new ReduceFunction<WaterSensor>() {
//            @Override
//            public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
//                Integer vc = value1.getVc();
//                long l = value1.getTs() + value2.getTs();
//                value1.setVc(vc);
//                value1.setTs(l);
//                return value1;
//            }
//        }).print();

//maxBy
        keyedStream.reduce(new ReduceFunction<WaterSensor>() {
            @Override
            public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                Integer vc = value2.getVc();
                long l = value1.getTs() + value2.getTs();
                value1.setVc(vc);
                value1.setTs(l);
                return value1;
            }
        }).print();
        env.execute();
    }
}
